package library.net.retrofit.interceptor;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author Created by qiang.hou on 2017/12/14.
 * @version 1.0
 */
public abstract class BaseParamsInterceptor implements Interceptor {

    public Map<String, Object> contentMap = new HashMap<>();

    public enum Type {
        ADD, UPDATE, REMOVE
    }

    public Type control;

    public Type getControlType() {
        return control;
    }

    public void setControlType(Type control) {
        this.control = control;
    }

    /**
     * @param value header value
     * @return 检测非法字符之后的 value
     */
    public String getValueEncoded(String value) throws UnsupportedEncodingException {
        if (value == null) {
            return "null";
        }
        String newValue = value.replace("\n", "");
        for (int i = 0, length = newValue.length(); i < length; i++) {
            char c = newValue.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                return URLEncoder.encode(newValue, "UTF-8");
            }
        }
        return newValue;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        return chain.proceed(interceptor(chain.request()));
    }

    abstract Request interceptor(Request request) throws UnsupportedEncodingException;
}
